package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping(value = "/login")
    public String toLogin() {
        // 由于login.jsp页面不在WEB-INF下，所以不能返回逻辑视图名称
// 需要使用forward:前缀告知SpringMVC转发到根路径下的login.jsp
        return "forward:/login.jsp";
    }

    /**
     * 登录接口
     *
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password) {
        SysUser loginUser = sysUserService.login(account, password);
        if (loginUser != null) {
            // 登录成功，用户信息存入 session
            session(Constants.SESSION_USER, loginUser);
            //重定向到后台首页
            return redirect("/main/index");
        } else {
            // 登录失败抛出异常
            throw new RuntimeException("登录失败，用户名或密码错误！ ");
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        session().invalidate();
        return redirect("/login");
    }

    // 跳转到后台首页
    @GetMapping("/main/index")
    public String index() {
        return "index";
    }

    @ExceptionHandler(value = RuntimeException.class)
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        // 设置捕获的错误对象到 request 作用域
        request.setAttribute(Constants.REQUEST_ERROR, e);
        // 跳转异常页面： /WEB-INF/jsp/500.jsp
        return "500";
    }
}
